//
//  LGPatientWeightController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/3/3.
//  体重

#import "LGPatientWeightController.h"

//统计图
#import "LGPatientWeightChart.h"
#import "LGMonitoringHistoryView.h"
#import "LGPatientWeightCell.h"
//区头
#import "LGPatientWeightHeader.h"
#import "LGChartDetailAlertView.h"

#import "LGPickerView.h"
@interface LGPatientWeightController ()<LGPatientWeightChartDelegate,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIView *footerView;
/**   */
@property (nonatomic , strong)LGPatientWeightChart *chartView;
/**   */
@property (nonatomic , strong)LGMonitoringHistoryView *historyView;
/**   */
@property (nonatomic , strong)LGChartDetailAlertView *alertView;
/**   */
@property (nonatomic , copy)NSString *monthString;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter1;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter2;
/**   */
@property (nonatomic , assign)BOOL firstLoad;
@end

@implementation LGPatientWeightController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.firstLoad = YES;
    self.monthString = [self.formatter2 stringFromDate:[NSDate date]];
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.alertView];
    self.emptyView.userInteractionEnabled = NO;
    self.emptyView.backgroundColor = [UIColor clearColor];
}

//模块被选中
-(void)viewWillAppearAction{
    if(self.firstLoad == YES){
        [self requestData];
        [self requestHistoryData];
        self.firstLoad = NO;
    }
    if(self.chartView.dataDic.allKeys.count == 0){
        [self requestData];
    }
    if (self.dataArray.count == 0) {
        [self requestHistoryData];
    }
}


//统计图数据
-(void)requestData{
    [RequestUtil withPOST:@"/doctor/patient.Physicalsign/bmiEcharts" parameters:@{@"timeframe":@"30",@"patient_id":self.patientid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        if(code == 200){
            self.chartView.dataDic = returnData;
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
    }];
    if (self.dataArray.count == 0) {
        [self requestHistoryData];
    }
}

//请求历史记录
-(void)requestHistoryData{
    [RequestUtil withPOST:@"/doctor/patient.Physicalsign/bmiList" parameters:@{@"timeframe":self.monthString,@"patient_id":self.patientid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(code == 200){
            self.dataArray = returnData;
            [self.tableView reloadData];
        }
        if(self.dataArray.count == 0){
            self.footerView.frame = CGRectMake(0, 0, Screen_W, viewPix(300));
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:viewPix(60)];
        }else{
            self.footerView.frame = CGRectMake(0, 0, Screen_W, viewPix(10));
        }
        self.tableView.tableFooterView = self.footerView;
    } error:^(NSError *error) {
        self.isfirst = NO;
        if(self.dataArray.count == 0){
            self.footerView.frame = CGRectMake(0, 0, Screen_W, viewPix(300));
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:viewPix(60)];
        }else{
            self.footerView.frame = CGRectMake(0, 0, Screen_W, viewPix(10));
        }
        self.tableView.tableFooterView = self.footerView;
    }];
}

//选择月份
-(void)showMonthPickerView{
    NSMutableArray *yearArray = [NSMutableArray array];
    NSArray *monthArray = @[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12"];
    for (NSInteger i=2020; i<2100; i++) {
        [yearArray addObject:[NSString stringWithFormat:@"%ld",i]];
    }
    LGPickerView *pickerView = [[LGPickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.pickArry = @[yearArray,monthArray];
    pickerView.units = @[@"年",@"月"];
    pickerView.selectStr = [self.monthString stringByReplacingOccurrencesOfString:@"-" withString:@"|"];
    [self.view.window addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectPickViewResult = ^(NSArray *resultArray) {
        weakSelf.historyView.monthLabel.text = [NSString stringWithFormat:@"%@年%@月",resultArray[0],resultArray[1]];
        weakSelf.monthString = [NSString stringWithFormat:@"%@-%@",resultArray[0],resultArray[1]];
        [weakSelf requestHistoryData];
    };
}

//点击某点的弹框
-(void)showAlertView:(NSDictionary *)weightDic  waistlineDic:(NSDictionary *)waistlineDic  date:(NSString *)dateString  point:(CGPoint)point{
    NSString *waistline = LGNSString(waistlineDic[@"value"]);
    CGFloat height = waistline.length>0?viewPix(80):viewPix(60);
    CGFloat marginX = (point.x>Screen_W/2.0)?(point.x-viewPix(150)-5):(point.x+5);
    self.alertView.frame = CGRectMake(marginX, point.y+3, viewPix(150), height);
    self.alertView.dateString = dateString;
    self.alertView.dataArray = waistline.length>0?@[@{@"icon":@"",@"title":@"体重",@"score":[NSString stringWithFormat:@"%@kg",weightDic[@"value"]] ,@"status":LGNSString(weightDic[@"status"])},@{@"icon":@"",@"title":@"腰围",@"score":[NSString stringWithFormat:@"%@cm",waistlineDic[@"value"]] ,@"status":LGNSString(waistlineDic[@"status"])}]
    :@[@{@"icon":@"",@"title":@"体重",@"score":[NSString stringWithFormat:@"%@kg",weightDic[@"value"]] ,@"status":LGNSString(weightDic[@"status"])}];
    self.alertView.hidden = NO;
    [self.tableView bringSubviewToFront:self.alertView];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *tempArray = self.dataArray[section][@"children"];
    return tempArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGPatientWeightCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *tempArray = self.dataArray[indexPath.section][@"children"];
    cell.dataDic = tempArray[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return viewPix(75);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    LGPatientWeightHeader *headView = [[LGPatientWeightHeader alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(75))];
    headView.monthLabel.text = self.dataArray[section][@"record_date"];
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return viewPix(15);
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    LGCornerFooterView *footView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(15))];
    footView.shadowView.backgroundColor = [UIColor colorWithString:@"#F5FBFF"];
    footView.backgroundColor = [UIColor clearColor];
    footView.bottomMargin = viewPix(10);
    return footView;
}

-(void)chartViewTouchesBegan{
    self.alertView.hidden = YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self chartViewTouchesBegan];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self chartViewTouchesBegan];
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake(0, 0, Screen_W, self.view.bounds.size.height);
}

#pragma mark
#pragma mark ====> 创建控件

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, self.view.bounds.size.height) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGPatientWeightCell class] forCellReuseIdentifier:@"cell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = viewPix(35);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(465))];
        headerView.backgroundColor = [UIColor clearColor];
        [headerView addSubview:self.chartView];
        [headerView addSubview:self.historyView];
        _tableView.tableHeaderView = headerView;
        _tableView.tableFooterView = self.footerView;
    }
    return _tableView;
}

-(LGPatientWeightChart *)chartView{
    if(!_chartView){
        _chartView = [[LGPatientWeightChart alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(375))];
        _chartView.delegate = self;;
    }
    return _chartView;
}

-(LGMonitoringHistoryView *)historyView{
    if(!_historyView){
        _historyView = [[LGMonitoringHistoryView alloc] initWithFrame:CGRectMake(0, kMaxY(self.chartView.frame)+viewPix(10), Screen_W, viewPix(70))];
        _historyView.monthLabel.text = [self.formatter1 stringFromDate:[NSDate date]];
        [_historyView.monthBtn addTarget:self action:@selector(showMonthPickerView) forControlEvents:UIControlEventTouchUpInside];
    }
    return _historyView;
}

-(LGChartDetailAlertView *)alertView{
    if(!_alertView){
        _alertView = [[LGChartDetailAlertView alloc] initWithFrame:CGRectMake(0, 0, viewPix(150), viewPix(36))];
        _alertView.hidden = YES;
    }
    return _alertView;
}

-(UIView *)footerView{
    if(!_footerView){
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(300))];
        [self emptyViewWithSuperView:_footerView frame:_footerView.bounds];
    }
    return _footerView;
}

-(NSDateFormatter *)formatter1{
    if(!_formatter1){
        _formatter1 = [[NSDateFormatter alloc] init];
        _formatter1.dateFormat = @"YYYY年MM月";
    }
    return _formatter1;
}

-(NSDateFormatter *)formatter2{
    if(!_formatter2){
        _formatter2 = [[NSDateFormatter alloc] init];
        _formatter2.dateFormat = @"YYYY-MM";
    }
    return _formatter2;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
